{% extends "base.html" %}

{% block head %}
<!-- 使用本地文件 -->
<script src="{{ url_for('static', filename='js/chart.umd.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.min.js') }}"></script>
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .btn {
        padding: 8px 16px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-weight: 500;
        transition: background-color 0.2s;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }

    .spinner {
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1976d2;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        display: none;
        margin-left: 10px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .status-message {
        margin-top: 20px;
        padding: 15px;
        border-radius: 4px;
        display: none;
    }

    .status-message.success {
        background-color: #e8f5e9;
        color: #2e7d32;
        border: 1px solid #c8e6c9;
    }

    .status-message.error {
        background-color: #ffebee;
        color: #c62828;
        border: 1px solid #ffcdd2;
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        margin: 20px -20px;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: normal;
        word-break: break-word;
        min-width: 120px;
        height: auto;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    .loading {
        text-align: center;
        padding: 20px;
        display: none;
    }

    .loading.active {
        display: block;
    }

    /* 添加筛选区域样式 */
    .filter-area {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        padding: 20px;
        margin: 20px 0;
    }

    .filter-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid var(--border-color);
    }

    .filter-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .filter-section {
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .filter-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .filter-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .filter-section-buttons {
        display: flex;
        gap: 8px;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    .folder-list {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .folder-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .folder-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .folder-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
    }

    .relatives-select-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 1px solid var(--primary-color);
        color: var(--primary-color);
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
    }

    .relatives-select-btn:hover {
        background: var(--primary-color);
        color: white;
    }

    .relatives-select-btn .selected-count {
        background: var(--primary-color);
        color: white;
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 12px;
    }

    .relatives-select-btn:hover .selected-count {
        background: white;
        color: var(--primary-color);
    }

    .table-actions {
        display: flex;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 15px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .left-actions, .right-actions {
        display: flex;
        gap: 10px;
    }

    .btn-outline-primary {
        background-color: white;
        color: var(--primary-color);
        border: 1px solid var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    /* 添加操作按钮区域样式 */
    .action-buttons {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        padding: 15px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .action-buttons .btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .action-buttons .btn-primary {
        background: var(--primary-color);
        color: white;
        border: 1px solid var(--primary-color);
    }

    .action-buttons .btn-primary:hover {
        background: var(--primary-hover);
        border-color: var(--primary-hover);
    }

    .action-buttons .btn-primary:disabled {
        background: #ccc;
        border-color: #ccc;
        cursor: not-allowed;
    }

    .action-buttons .spinner {
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-top-color: white;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-left: 8px;
    }

    /* 亲属选择模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 5% auto;
        padding: 25px;
        border: 1px solid #888;
        width: 80%;
        max-width: 800px;
        border-radius: 8px;
        max-height: 80vh;
        overflow-y: auto;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ddd;
    }

    .modal-title {
        font-size: 1.2rem;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .close-button {
        color: #aaa;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }

    .close-button:hover {
        color: black;
    }

    .modal-footer {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #ddd;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .relatives-section {
        margin-top: 10px;
        margin-bottom: 15px;
        padding: 15px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        width: 100%;
    }

    .relatives-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 8px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .relatives-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-list {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 15px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    .relative-item {
        display: flex;
        align-items: center;
        padding: 10px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        transition: all 0.2s ease;
        min-width: 0;
    }

    .relative-item:hover {
        background: #f8f9fa;
        border-color: var(--primary-color);
    }

    .relative-item input[type="checkbox"] {
        margin-right: 8px;
        min-width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .relative-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
        min-width: 0;
    }

    /* 适配小屏幕 */
    @media (max-width: 1200px) {
        .relatives-list {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    @media (max-width: 768px) {
        .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 480px) {
        .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
    }

    /* 新增：交易类型选择样式 */
    .type-list {
        display: flex;
        flex-direction: column;
        gap: 10px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
    }

    .type-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .type-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .type-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
    }

    /* 修改图表容器样式 */
    .charts-container {
        display: grid;
        grid-template-columns: repeat(2, 1fr); /* 修改为固定2列 */
        gap: 20px;
        margin-top: 20px;
        padding: 20px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        max-width: 1200px; /* 限制最大宽度 */
        margin-left: auto;
        margin-right: auto;
    }

    .chart-wrapper {
        background: white;
        border-radius: 8px;
        padding: 15px;
        border: 1px solid #e0e0e0;
        width: 100%;
        max-width: 550px; /* 限制每个图表容器的最大宽度 */
        margin: 0 auto;
    }

    .chart-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin-bottom: 15px;
        text-align: center;
        padding: 0 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .chart-canvas {
        width: 100%;
        height: 400px; /* 固定高度 */
        max-height: 400px;
    }

    /* 添加响应式布局 */
    @media (max-width: 1200px) {
        .charts-container {
            grid-template-columns: repeat(2, 1fr);
            padding: 15px;
        }
        
        .chart-wrapper {
            max-width: 450px;
        }
    }

    @media (max-width: 900px) {
        .charts-container {
            grid-template-columns: 1fr;
            max-width: 600px;
        }
        
        .chart-wrapper {
            max-width: 100%;
        }
        
        .chart-canvas {
            height: 350px;
        }
    }

    /* 字段选择按钮样式 */
    .field-select-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 1px solid var(--primary-color);
        color: var(--primary-color);
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
    }

    .field-select-btn:hover {
        background: var(--primary-color);
        color: white;
    }

    .field-select-btn .selected-count {
        background: var(--primary-color);
        color: white;
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 12px;
    }

    .field-select-btn:hover .selected-count {
        background: white;
        color: var(--primary-color);
    }

    /* 字段选择模态框样式 */
    .field-modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }

    .field-modal-content {
        background-color: #fefefe;
        margin: 5% auto;
        padding: 25px;
        border: 1px solid #888;
        width: 80%;
        max-width: 800px;
        border-radius: 8px;
        max-height: 80vh;
        overflow-y: auto;
    }

    .field-modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ddd;
    }

    .field-modal-title {
        font-size: 1.2rem;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .field-modal-footer {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #ddd;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .field-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
        margin-bottom: 15px;
    }

    .field-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        background: white;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
        cursor: move;
    }

    .field-item input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .field-item label {
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: var(--text-color);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .field-item.dragging {
        opacity: 0.5;
        border: 2px dashed var(--primary-color);
    }

    .field-item.drag-over {
        border: 2px solid var(--primary-color);
    }

    .field-actions {
        display: flex;
        justify-content: flex-start;
        gap: 10px;
        margin-bottom: 15px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>银行流水分析</h2>
        </div>
        <div class="card-body">
            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-primary" id="loadDataBtn">
                    加载已有数据
                    <div id="loadingSpinner" class="spinner"></div>
                </button>
                <button type="button" class="btn btn-primary" id="analyzeDataBtn">
                    分析数据
                    <div id="analyzeSpinner" class="spinner"></div>
                </button>
            </div>

            <!-- 状态消息 -->
            <div id="statusMessage" class="status-message"></div>

            <!-- 筛选区域 -->
            <div id="filterArea" class="filter-area" style="display: none;">
                <div class="filter-header">
                    <h3 class="filter-title">筛选条件</h3>
                </div>
                <div class="filter-content">
                    <!-- 文件夹选择部分 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">选择被审查人：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllFoldersBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllFoldersBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="folderList" class="folder-list"></div>
                    </div>

                    <!-- 亲属选择按钮 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">亲属选择：</div>
                            <button type="button" class="relatives-select-btn" id="relativesSelectBtn">
                                选择亲属
                                <span class="selected-count" id="selectedRelativesCount">0</span>
                            </button>
                        </div>
                    </div>

                    <!-- 新增：交易类型选择部分 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">交易类型：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllTypesBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllTypesBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="typeList" class="type-list">
                            <div class="type-item">
                                <input type="checkbox" id="type-income" value="收入">
                                <label for="type-income">收入</label>
                            </div>
                            <div class="type-item">
                                <input type="checkbox" id="type-expense" value="一般支出">
                                <label for="type-expense">一般支出</label>
                            </div>
                            <div class="type-item">
                                <input type="checkbox" id="type-other" value="其他">
                                <label for="type-other">其他</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 亲属选择模态框 -->
            <div id="relativesModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">选择亲属</h3>
                        <span class="close-button" id="closeRelativesModal">&times;</span>
                    </div>
                    <div id="relativesList"></div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelRelativesSelection">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmRelativesSelection">确定</button>
                    </div>
                </div>
            </div>

            <!-- 表格操作按钮 -->
            <div class="table-actions" style="display: none;">
                <div class="left-actions">
                    <button type="button" class="field-select-btn" id="fieldSelectBtn">
                        选择显示字段
                        <span class="selected-count" id="selectedFieldsCount">0</span>
                    </button>
                    <button type="button" class="btn btn-primary" id="downloadExcelBtn">下载Excel</button>
                </div>
                <div class="right-actions">
                    <button type="button" class="btn btn-primary" id="applyFilterBtn">应用筛选</button>
                    <button type="button" class="btn btn-outline-primary" id="cancelFilterBtn">取消筛选</button>
                </div>
            </div>

            <!-- 字段选择模态框 -->
            <div id="fieldModal" class="field-modal">
                <div class="field-modal-content">
                    <div class="field-modal-header">
                        <h3 class="field-modal-title">选择显示字段</h3>
                        <span class="close-button" id="closeFieldModal">&times;</span>
                    </div>
                    <div class="field-actions">
                        <button type="button" class="btn btn-sm btn-primary" id="selectAllFieldsBtn">全选</button>
                        <button type="button" class="btn btn-sm btn-primary" id="deselectAllFieldsBtn">取消全选</button>
                    </div>
                    <div id="fieldList" class="field-list"></div>
                    <div class="field-modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelFieldSelection">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmFieldSelection">确定</button>
                    </div>
                </div>
            </div>

            <!-- 加载动画 -->
            <div id="loading" class="loading">
                正在加载数据，请稍候...
            </div>

            <!-- 结果表格 -->
            <div id="resultContainer" class="card" style="display: none;">
                <div class="table-wrapper">
                    <div class="table-container">
                        <table class="result-table">
                            <thead>
                                <tr id="tableHeader"></tr>
                            </thead>
                            <tbody id="tableBody"></tbody>
                        </table>
                    </div>
                    <div class="pagination-container">
                        <div class="pagination" id="pagination"></div>
                    </div>
                </div>
            </div>

            <!-- 添加图表容器 -->
            <div id="chartsContainer" class="charts-container" style="display: none;"></div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 注册 datalabels 插件
    if (typeof Chart !== 'undefined' && typeof ChartDataLabels !== 'undefined') {
        Chart.register(ChartDataLabels);
    } else {
        console.error('Chart.js or DataLabels plugin not loaded properly');
        alert('图表组件加载失败，请检查文件是否正确放置在 static/js 目录下');
    }
    
    // 获取DOM元素
    const loadDataBtn = document.getElementById('loadDataBtn');
    const analyzeDataBtn = document.getElementById('analyzeDataBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const analyzeSpinner = document.getElementById('analyzeSpinner');
    const statusMessage = document.getElementById('statusMessage');
    const filterArea = document.getElementById('filterArea');
    const folderList = document.getElementById('folderList');
    const tableActions = document.querySelector('.table-actions');

    let currentPage = 1;
    let totalPages = 1;
    let cachedData = null;
    let itemsPerPage = 20;
    let allData = null;

    // 存储亲属数据的Map
    let relativesMap = new Map();
    // 添加一个持久化的选中状态存储
    let persistentSelectedRelatives = new Set();

    // 获取亲属选择相关的DOM元素
    const relativesModal = document.getElementById('relativesModal');
    const relativesSelectBtn = document.getElementById('relativesSelectBtn');
    const closeRelativesModal = document.getElementById('closeRelativesModal');
    const cancelRelativesSelection = document.getElementById('cancelRelativesSelection');
    const confirmRelativesSelection = document.getElementById('confirmRelativesSelection');
    const selectedRelativesCount = document.getElementById('selectedRelativesCount');

    // 临时存储选中的亲属，用于取消操作
    let tempSelectedRelatives = new Set();

    // 存储图表实例的Map
    let chartInstances = new Map();

    // 存储所有可用字段和选中的字段
    let availableFields = [];
    let selectedFields = new Set();
    let fieldOrder = [];
    // 添加临时存储，用于取消操作
    let tempSelectedFields = new Set();
    let tempFieldOrder = [];

    // 获取字段选择相关的DOM元素
    const fieldModal = document.getElementById('fieldModal');
    const fieldSelectBtn = document.getElementById('fieldSelectBtn');
    const closeFieldModal = document.getElementById('closeFieldModal');
    const cancelFieldSelection = document.getElementById('cancelFieldSelection');
    const confirmFieldSelection = document.getElementById('confirmFieldSelection');
    const selectedFieldsCount = document.getElementById('selectedFieldsCount');

    // 生成随机颜色
    function generateColors(count) {
        const colors = [];
        for (let i = 0; i < count; i++) {
            const hue = (i * 137.508) % 360; // 使用黄金角来生成分散的色相值
            colors.push(`hsl(${hue}, 70%, 60%)`);
        }
        return colors;
    }

    // 加载数据
    async function loadFullData() {
        try {
            loadingSpinner.style.display = 'inline-block';
            loadDataBtn.disabled = true;
            document.getElementById('loading').classList.add('active');

            const response = await fetch('/bank-flow-bak/load-data');
            const result = await response.json();

            if (result.success) {
                statusMessage.textContent = '数据加载成功';
                statusMessage.className = 'status-message success';
                statusMessage.style.display = 'block';

                // 存储文件夹和亲属数据
                allData = result;
                relativesMap.clear();
                
                // 显示文件夹列表
                folderList.innerHTML = '';
                result.folders.forEach(folder => {
                    const folderItem = document.createElement('div');
                    folderItem.className = 'folder-item';
                    
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.id = folder.name;
                    checkbox.value = folder.name;
                    checkbox.addEventListener('change', () => {
                        console.log(`[DEBUG] 文件夹 ${folder.name} 的选中状态改变`);
                        updateRelativesList();
                    });
                    
                    const label = document.createElement('label');
                    label.htmlFor = folder.name;
                    label.textContent = folder.name;
                    
                    folderItem.appendChild(checkbox);
                    folderItem.appendChild(label);
                    folderList.appendChild(folderItem);

                    // 存储亲属数据
                    if (folder.relatives && Array.isArray(folder.relatives)) {
                        console.log(`[DEBUG] 存储文件夹 ${folder.name} 的亲属数据:`, folder.relatives);
                        relativesMap.set(folder.name, folder.relatives);
                    }
                });

                // 显示筛选区域和表格操作按钮
                filterArea.style.display = 'block';
                tableActions.style.display = 'flex';

                // 缓存数据并显示
                cachedData = result.data;
                totalPages = Math.ceil(cachedData.length / itemsPerPage);
                currentPage = 1;
                displayPageData();

                // 渲染图表
                renderCharts(cachedData);

                // 初始化字段列表
                initializeFieldList(result.data);
            } else {
                statusMessage.textContent = result.error || '加载数据失败';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            }
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = '加载数据时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        } finally {
            loadingSpinner.style.display = 'none';
            loadDataBtn.disabled = false;
            document.getElementById('loading').classList.remove('active');
        }
    }

    // 打开亲属选择模态框
    relativesSelectBtn.addEventListener('click', () => {
        // 更新亲属列表
        updateRelativesList();
        // 保存当前选中状态到临时存储
        tempSelectedRelatives = new Set(persistentSelectedRelatives);
        // 显示模态框
        relativesModal.style.display = 'block';
    });

    // 修改确认按钮的处理函数
    confirmRelativesSelection.addEventListener('click', () => {
        // 更新持久化的选中状态
        persistentSelectedRelatives = new Set(getSelectedRelatives());
        // 更新选中计数
        selectedRelativesCount.textContent = persistentSelectedRelatives.size;
        relativesModal.style.display = 'none';
    });

    // 修改取消按钮的处理函数
    cancelRelativesSelection.addEventListener('click', () => {
        // 恢复之前的选中状态
        const checkboxes = document.querySelectorAll('#relativesList input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = tempSelectedRelatives.has(cb.value);
        });
        relativesModal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === relativesModal) {
            relativesModal.style.display = 'none';
        }
    });

    // 关闭按钮事件
    closeRelativesModal.addEventListener('click', () => {
        relativesModal.style.display = 'none';
    });

    // 修改updateRelativesList函数
    function updateRelativesList() {
        const relativesListContainer = document.getElementById('relativesList');
        relativesListContainer.innerHTML = '';
        
        const selectedFolders = getSelectedFolders();
        console.log('[DEBUG] 选中的文件夹:', selectedFolders);

        if (selectedFolders.length === 0) {
            relativesListContainer.innerHTML = '<div style="text-align: center; padding: 20px;">请先选择被审查人</div>';
            return;
        }

        // 为每个选中的文件夹创建一个亲属区域
        selectedFolders.forEach(folderName => {
            console.log(`[DEBUG] 处理文件夹 ${folderName} 的亲属数据`);
            const relatives = relativesMap.get(folderName) || [];
            console.log(`[DEBUG] 文件夹 ${folderName} 的亲属数据:`, relatives);

            if (relatives.length > 0) {
                // 创建文件夹的亲属区域
                const relativesSection = document.createElement('div');
                relativesSection.className = 'relatives-section';

                // 创建区域标题和按钮
                const sectionHeader = document.createElement('div');
                sectionHeader.className = 'relatives-section-header';

                const sectionTitle = document.createElement('div');
                sectionTitle.className = 'relatives-section-title';
                sectionTitle.textContent = `${folderName} 的亲属`;

                const buttonGroup = document.createElement('div');
                buttonGroup.className = 'filter-section-buttons';

                const selectAllBtn = document.createElement('button');
                selectAllBtn.type = 'button';
                selectAllBtn.className = 'btn btn-sm btn-primary';
                selectAllBtn.textContent = '全选';
                selectAllBtn.onclick = () => selectAllRelativesInFolder(folderName);

                const deselectAllBtn = document.createElement('button');
                deselectAllBtn.type = 'button';
                deselectAllBtn.className = 'btn btn-sm btn-primary';
                deselectAllBtn.textContent = '取消全选';
                deselectAllBtn.onclick = () => deselectAllRelativesInFolder(folderName);

                buttonGroup.appendChild(selectAllBtn);
                buttonGroup.appendChild(deselectAllBtn);
                sectionHeader.appendChild(sectionTitle);
                sectionHeader.appendChild(buttonGroup);
                relativesSection.appendChild(sectionHeader);

                // 创建亲属列表
                const relativesList = document.createElement('div');
                relativesList.className = 'relatives-list';
                relativesList.id = `relatives-${folderName}`;

                relatives.forEach(([name, relation]) => {
                    if (name && relation) {
                        const relativeItem = document.createElement('div');
                        relativeItem.className = 'relative-item';
                        
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.id = `relative-${folderName}-${name}`;
                        checkbox.value = name;
                        checkbox.dataset.folder = folderName;
                        // 使用持久化的选中状态
                        checkbox.checked = persistentSelectedRelatives.has(name);
                        checkbox.addEventListener('change', () => {
                            console.log(`[DEBUG] 亲属 ${name} 的选中状态改变`);
                            updateSelectedCount();
                        });
                        
                        const label = document.createElement('label');
                        label.htmlFor = `relative-${folderName}-${name}`;
                        label.textContent = `${name}（${relation}）`;
                        
                        relativeItem.appendChild(checkbox);
                        relativeItem.appendChild(label);
                        relativesList.appendChild(relativeItem);
                    }
                });

                relativesSection.appendChild(relativesList);
                relativesListContainer.appendChild(relativesSection);
            }
        });

        // 更新选中计数
        updateSelectedCount();
    }

    // 更新选中的亲属数量
    function updateSelectedCount() {
        const checkedCount = document.querySelectorAll('#relativesList input[type="checkbox"]:checked').length;
        selectedRelativesCount.textContent = checkedCount;
    }

    // 全选指定文件夹的亲属
    function selectAllRelativesInFolder(folderName) {
        const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        updateSelectedCount();
    }

    // 取消全选指定文件夹的亲属
    function deselectAllRelativesInFolder(folderName) {
        const checkboxes = document.querySelectorAll(`#relatives-${folderName} input[type="checkbox"]`);
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        updateSelectedCount();
    }

    // 获取所有选中的亲属
    function getSelectedRelatives() {
        const checkboxes = document.querySelectorAll('#relativesList input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    // 获取选中的文件夹
    function getSelectedFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    // 全选文件夹
    function selectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        updateRelativesList();
    }

    // 取消全选文件夹
    function deselectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        updateRelativesList();
    }

    // 分析数据
    async function analyzeData() {
        try {
            analyzeSpinner.style.display = 'inline-block';
            analyzeDataBtn.disabled = true;

            // 调用后端接口分析数据
            const response = await fetch('/bank-flow-bak/analyze', {
                method: 'POST'
            });
            const result = await response.json();

            if (result.success) {
                statusMessage.textContent = '数据分析完成';
                statusMessage.className = 'status-message success';
                // 重新加载数据
                await loadFullData();
            } else {
                statusMessage.textContent = result.error || '数据分析失败';
                statusMessage.className = 'status-message error';
            }
            statusMessage.style.display = 'block';
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = '分析数据时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        } finally {
            analyzeSpinner.style.display = 'none';
            analyzeDataBtn.disabled = false;
        }
    }

    // 显示分页数据
    function displayPageData(page = currentPage) {
        if (!cachedData) return;

        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const pageData = cachedData.slice(start, end);

        const container = document.getElementById('resultContainer');
        const tableHeader = document.getElementById('tableHeader');
        const tableBody = document.getElementById('tableBody');

        // 清空现有内容
        tableHeader.innerHTML = '';
        tableBody.innerHTML = '';

        if (!pageData || pageData.length === 0) {
            container.style.display = 'none';
            return;
        }

        // 使用选中的字段和字段顺序生成表头
        fieldOrder.forEach(column => {
            if (selectedFields.has(column)) {
                const th = document.createElement('th');
                th.textContent = column;
                tableHeader.appendChild(th);
            }
        });

        // 生成表格内容
        pageData.forEach(row => {
            const tr = document.createElement('tr');
            fieldOrder.forEach(column => {
                if (selectedFields.has(column)) {
                    const td = document.createElement('td');
                    const value = row[column];
                    
                    // 处理数值类型的显示格式
                    if (typeof value === 'number') {
                        td.style.textAlign = 'right';
                        td.textContent = value.toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    } else {
                        td.textContent = value || '';
                    }
                    
                    tr.appendChild(td);
                }
            });
            tableBody.appendChild(tr);
        });

        // 更新分页
        updatePagination();
        container.style.display = 'block';
    }

    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        if (totalPages <= 1) return;

        // 上一页
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = currentPage === 1;
        prevButton.onclick = () => {
            if (currentPage > 1) {
                currentPage--;
                displayPageData();
            }
        };
        pagination.appendChild(prevButton);

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (
                i === 1 || // 第一页
                i === totalPages || // 最后一页
                (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近
            ) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.classList.toggle('active', i === currentPage);
                pageButton.onclick = () => {
                    currentPage = i;
                    displayPageData();
                };
                pagination.appendChild(pageButton);
            } else if (
                i === currentPage - 3 || // 当前页前的省略号
                i === currentPage + 3 // 当前页后的省略号
            ) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }
        }

        // 下一页
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = currentPage === totalPages;
        nextButton.onclick = () => {
            if (currentPage < totalPages) {
                currentPage++;
                displayPageData();
            }
        };
        pagination.appendChild(nextButton);
    }

    // 新增：交易类型选择相关函数
    function selectAllTypes() {
        const checkboxes = document.querySelectorAll('#typeList input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
    }

    function deselectAllTypes() {
        const checkboxes = document.querySelectorAll('#typeList input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
    }

    // 获取选中的交易类型
    function getSelectedTypes() {
        const checkboxes = document.querySelectorAll('#typeList input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    // 渲染图表函数
    function renderCharts(data) {
        if (!data || data.length === 0) return;

        const chartsContainer = document.getElementById('chartsContainer');
        chartsContainer.innerHTML = '';

        // 销毁现有的图表实例
        chartInstances.forEach(chart => chart.destroy());
        chartInstances.clear();

        // 按文件夹分组数据
        const folderGroups = new Map();
        data.forEach(record => {
            if (!folderGroups.has(record.文件夹)) {
                folderGroups.set(record.文件夹, []);
            }
            folderGroups.get(record.文件夹).push(record);
        });

        // 获取当前选中的交易类型
        const selectedTypes = getSelectedTypes();
        const useDetailedType = selectedTypes.length === 1 && 
            (selectedTypes[0] === '收入' || selectedTypes[0] === '一般支出');

        // 为每个文件夹创建饼图
        folderGroups.forEach((records, folder) => {
            // 按类型分组并计算金额总和
            const typeGroups = new Map();
            records.forEach(record => {
                // 根据筛选条件决定使用哪个字段作为分组依据
                const type = useDetailedType ? (record.详细类型 || '未分类') : (record.类型 || '未分类');
                const amount = Math.abs(parseFloat(record.交易金额) || 0);
                if (!typeGroups.has(type)) {
                    typeGroups.set(type, 0);
                }
                typeGroups.set(type, typeGroups.get(type) + amount);
            });

            // 创建图表容器
            const chartWrapper = document.createElement('div');
            chartWrapper.className = 'chart-wrapper';
            
            const chartTitle = document.createElement('div');
            chartTitle.className = 'chart-title';
            chartTitle.textContent = `${folder} - ${useDetailedType ? selectedTypes[0] + '详细类型' : '交易类型'}金额分布`;
            
            const canvas = document.createElement('canvas');
            canvas.className = 'chart-canvas';
            
            chartWrapper.appendChild(chartTitle);
            chartWrapper.appendChild(canvas);
            chartsContainer.appendChild(chartWrapper);

            // 准备图表数据
            const types = Array.from(typeGroups.keys());
            const amounts = Array.from(typeGroups.values());
            const total = amounts.reduce((a, b) => a + b, 0);

            // 准备数据并按金额降序排序
            const chartData = types.map((type, index) => ({
                type,
                amount: amounts[index],
                percentage: (amounts[index] / total) * 100
            })).sort((a, b) => b.amount - a.amount);

            // 创建饼图
            const ctx = canvas.getContext('2d');
            const chart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: chartData.map(item => item.type),
                    datasets: [{
                        data: chartData.map(item => item.amount),
                        backgroundColor: generateColors(chartData.length),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '50%',
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                generateLabels: function(chart) {
                                    return chartData.map((item, i) => ({
                                        text: `${item.type} (${item.percentage.toFixed(2)}%)`,
                                        fillStyle: chart.data.datasets[0].backgroundColor[i],
                                        hidden: false,
                                        index: i
                                    }));
                                }
                            }
                        },
                        tooltip: {
                            enabled: true,
                            callbacks: {
                                label: function(context) {
                                    const item = chartData[context.dataIndex];
                                    const formattedAmount = item.amount.toLocaleString('zh-CN', {
                                        style: 'currency',
                                        currency: 'CNY'
                                    });
                                    return [
                                        `金额：${formattedAmount}`,
                                        `占比：${item.percentage.toFixed(2)}%`
                                    ];
                                }
                            }
                        },
                        datalabels: {
                            color: '#fff',
                            font: {
                                weight: 'bold',
                                size: 12
                            },
                            formatter: function(value, context) {
                                const item = chartData[context.dataIndex];
                                if (item.percentage < 3) return ''; // 比例太小不显示标签
                                return `${item.percentage.toFixed(1)}%\n${(item.amount/10000).toFixed(0)}万`;
                            }
                        }
                    }
                }
            });

            // 存储图表实例
            chartInstances.set(folder, chart);
        });

        // 显示图表容器
        chartsContainer.style.display = 'grid';
    }

    // 修改应用筛选函数
    async function applyFilter() {
        const selectedFolders = getSelectedFolders();
        const selectedRelatives = Array.from(persistentSelectedRelatives);
        const selectedTypes = getSelectedTypes();
        
        if (selectedFolders.length === 0) {
            alert('请至少选择一个被审查人');
            return;
        }

        try {
            document.getElementById('loading').classList.add('active');
            
            const params = new URLSearchParams();
            selectedFolders.forEach(folder => {
                params.append('folders', folder);
            });
            selectedRelatives.forEach(relative => {
                params.append('relatives', relative);
            });
            selectedTypes.forEach(type => {
                params.append('types', type);
            });

            const response = await fetch(`/bank-flow-bak/filter-data?${params.toString()}`);
            const result = await response.json();

            if (result.success) {
                cachedData = result.data;
                totalPages = Math.ceil(cachedData.length / itemsPerPage);
                currentPage = 1;
                displayPageData();
                
                // 渲染图表
                renderCharts(result.data);
                
                statusMessage.textContent = `筛选完成，共找到 ${result.total_records} 条记录`;
                statusMessage.className = 'status-message success';
                statusMessage.style.display = 'block';
            } else {
                statusMessage.textContent = result.error || '筛选数据失败';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            }
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = '筛选数据时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        } finally {
            document.getElementById('loading').classList.remove('active');
        }
    }

    // 修改取消筛选函数
    async function cancelFilter() {
        try {
            // 清除所有选中状态
            const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
            allCheckboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // 清除持久化的选中状态
            persistentSelectedRelatives.clear();
            selectedRelativesCount.textContent = '0';
            
            // 清除图表
            const chartsContainer = document.getElementById('chartsContainer');
            chartsContainer.style.display = 'none';
            chartsContainer.innerHTML = '';
            chartInstances.forEach(chart => chart.destroy());
            chartInstances.clear();
            
            // 重新加载全量数据
            await loadFullData();
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = '取消筛选时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        }
    }

    // 初始化字段列表
    function initializeFieldList(data) {
        if (!data || data.length === 0) return;
        
        // 获取所有可用字段
        availableFields = Object.keys(data[0]);
        // 初始时全选所有字段
        selectedFields = new Set(availableFields);
        // 初始化字段顺序
        fieldOrder = [...availableFields];
        
        // 更新选中计数
        updateSelectedFieldsCount();
    }

    // 渲染字段列表
    function renderFieldList() {
        const fieldList = document.getElementById('fieldList');
        fieldList.innerHTML = '';
        
        fieldOrder.forEach((field, index) => {
            const fieldItem = document.createElement('div');
            fieldItem.className = 'field-item';
            fieldItem.draggable = true;
            fieldItem.dataset.field = field;
            
            // 添加拖拽事件监听器
            fieldItem.addEventListener('dragstart', handleDragStart);
            fieldItem.addEventListener('dragend', handleDragEnd);
            fieldItem.addEventListener('dragover', handleDragOver);
            fieldItem.addEventListener('drop', handleDrop);
            
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `field-${field}`;
            checkbox.checked = selectedFields.has(field);
            checkbox.addEventListener('change', () => {
                if (checkbox.checked) {
                    selectedFields.add(field);
                } else {
                    selectedFields.delete(field);
                }
            });
            
            const label = document.createElement('label');
            label.htmlFor = `field-${field}`;
            label.textContent = field;
            
            fieldItem.appendChild(checkbox);
            fieldItem.appendChild(label);
            fieldList.appendChild(fieldItem);
        });
    }

    // 拖拽相关函数
    function handleDragStart(e) {
        e.target.classList.add('dragging');
        e.dataTransfer.setData('text/plain', e.target.dataset.field);
    }

    function handleDragEnd(e) {
        e.target.classList.remove('dragging');
        document.querySelectorAll('.field-item').forEach(item => {
            item.classList.remove('drag-over');
        });
    }

    function handleDragOver(e) {
        e.preventDefault();
        e.target.closest('.field-item')?.classList.add('drag-over');
    }

    function handleDrop(e) {
        e.preventDefault();
        const draggedField = e.dataTransfer.getData('text/plain');
        const dropTarget = e.target.closest('.field-item');
        
        if (dropTarget && dropTarget.dataset.field !== draggedField) {
            const draggedIndex = fieldOrder.indexOf(draggedField);
            const dropIndex = fieldOrder.indexOf(dropTarget.dataset.field);
            
            // 更新字段顺序
            fieldOrder.splice(draggedIndex, 1);
            fieldOrder.splice(dropIndex, 0, draggedField);
            
            // 重新渲染字段列表
            renderFieldList();
        }
        
        document.querySelectorAll('.field-item').forEach(item => {
            item.classList.remove('drag-over');
        });
    }

    // 更新选中的字段数量
    function updateSelectedFieldsCount() {
        selectedFieldsCount.textContent = selectedFields.size;
    }

    // 全选字段
    function selectAllFields() {
        selectedFields = new Set(availableFields);
        renderFieldList();
    }

    // 取消全选字段
    function deselectAllFields() {
        selectedFields.clear();
        renderFieldList();
    }

    // 打开字段选择模态框
    fieldSelectBtn.addEventListener('click', () => {
        // 保存当前状态到临时存储
        tempSelectedFields = new Set(selectedFields);
        tempFieldOrder = [...fieldOrder];
        // 显示模态框
        fieldModal.style.display = 'block';
        // 更新字段列表
        renderFieldList();
    });

    // 关闭模态框的各种方式
    closeFieldModal.addEventListener('click', () => {
        cancelFieldSelection.click();
    });

    window.addEventListener('click', (event) => {
        if (event.target === fieldModal) {
            cancelFieldSelection.click();
        }
    });

    // 取消选择
    cancelFieldSelection.addEventListener('click', () => {
        // 恢复之前的状态
        selectedFields = new Set(tempSelectedFields);
        fieldOrder = [...tempFieldOrder];
        // 关闭模态框
        fieldModal.style.display = 'none';
    });

    // 确认选择
    confirmFieldSelection.addEventListener('click', () => {
        // 关闭模态框
        fieldModal.style.display = 'none';
        // 更新选中计数
        updateSelectedFieldsCount();
        // 重新渲染表格
        displayPageData();
    });

    // 绑定字段选择按钮事件
    document.getElementById('selectAllFieldsBtn').addEventListener('click', selectAllFields);
    document.getElementById('deselectAllFieldsBtn').addEventListener('click', deselectAllFields);

    // 绑定按钮事件
    loadDataBtn.addEventListener('click', loadFullData);
    analyzeDataBtn.addEventListener('click', analyzeData);
    document.getElementById('selectAllFoldersBtn').addEventListener('click', selectAllFolders);
    document.getElementById('deselectAllFoldersBtn').addEventListener('click', deselectAllFolders);
    document.getElementById('applyFilterBtn').addEventListener('click', applyFilter);
    document.getElementById('cancelFilterBtn').addEventListener('click', cancelFilter);

    // 绑定交易类型按钮事件
    document.getElementById('selectAllTypesBtn').addEventListener('click', selectAllTypes);
    document.getElementById('deselectAllTypesBtn').addEventListener('click', deselectAllTypes);

    // 获取下载按钮元素
    const downloadExcelBtn = document.getElementById('downloadExcelBtn');

    // 下载Excel文件
    async function downloadExcel() {
        try {
            // 获取筛选条件
            const selectedFolders = getSelectedFolders();
            const selectedRelatives = Array.from(persistentSelectedRelatives);
            const selectedTypes = getSelectedTypes();
            
            // 获取当前表格中显示的字段（按照显示顺序）
            const displayedFields = fieldOrder.filter(field => selectedFields.has(field));

            if (selectedFolders.length === 0) {
                alert('请至少选择一个被审查人');
                return;
            }

            // 构建URL参数
            const params = new URLSearchParams();
            selectedFolders.forEach(folder => {
                params.append('folders', folder);
            });
            selectedRelatives.forEach(relative => {
                params.append('relatives', relative);
            });
            selectedTypes.forEach(type => {
                params.append('types', type);
            });
            displayedFields.forEach(field => {
                params.append('fields', field);
            });

            const downloadUrl = `/bank-flow-bak/download-excel?${params.toString()}`;
            
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            statusMessage.textContent = '文件下载成功';
            statusMessage.className = 'status-message success';
            statusMessage.style.display = 'block';
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = error.message || '下载文件时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        }
    }

    // 绑定下载按钮事件
    downloadExcelBtn.addEventListener('click', downloadExcel);

    // 初始加载数据
    loadFullData();
});
</script>
{% endblock %}